<?php

namespace Mlym\CodeGeneration\ControllerGeneration\Method;


use Mlym\CodeGeneration\Middleware\Bean\View\ViewColumnBean;

class Add extends MethodAbstract
{
    protected $methodName = 'add';
    protected $methodDescription = '新增数据';
    protected $methodAllow = 'POST';

    function addMethodBody()
    {
        $method = $this->method;
        $modelName = $this->getModelName();
        $methodBody = <<<Body
\$param = ContextManager::getInstance()->get('param');
\$data = [

Body;

        $this->chunkSchemaColumn(function (ViewColumnBean $column) use (&$methodBody) {
            $param = $this->buildValidateColumnParam($column);
            $isPrimary = $this->controllerConfig->getTable()->getTableName() == $column->getModule() && $this->controllerConfig->getTable()->getPkFiledName() == $column->getName();

            if (!$isPrimary && !in_array($column->getName(), $this->ignoreField)) {
                $methodBody .= "    '{$column->getName()}' => \$param['{$column->getName()}'],\n";
                $this->addColumnComment($param);
            }
            return false;
        });

        $methodBody .= <<<Body
];
\$model = new {$modelName}(\$data);
\$model->save();
\$this->writeJson(Status::CODE_OK, \$model->toArray(), "操作成功");

Body;

        //配置方法内容
        $method->setBody($methodBody);
    }


    function addComment()
    {
        $this->method->addComment("@throws \Throwable");
    }
}
